<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/15
 * Time: 14:17
 */

namespace Home\Controller;
use Think\Controller;

class GoodController extends CommonController
{
    private $Goods='';
    private $Cart='';
    private $userID='';

    function __construct()
    {
        parent::__construct();
        $this->Goods=D('Goods');
        $this->Cart=D('Cart');
        $this->userID=session("userID");
        $this->Cart->startTrans();
    }

    // $id 为商品的ID
    function GoodInfo($id='')
    {
        $arr=$this->Goods->where("id=".$id)->find();

        if($arr['seller_id']!="0")
        {
            $arr['thumb_b']='seller/thumb/'.$arr['thumb'];
        }else{
            $arr['thumb_b']='thumb/'.$arr['thumb'];
        }

        $cartNum=$this->Cart->where("user_id=".$this->userID)->sum('number');
        if($cartNum)
        {
            $this->Cart->commit();
        }else{
            $this->Cart->rollback();
        }

        $cartNumPrice=$this->Cart->where("user_id=".$this->userID)->select();

        $cartPrice='';
        foreach($cartNumPrice as $key=>$r)
        {
            $cartPrice += $r['shop_price']*$r['number'];
            if($arr['id']==$r['goods_id'])
            {
                $isCartNum=$r['number'];
            }
        }

        if($isCartNum!="")
        {
            $this->assign("isCartNum",$isCartNum);
        }else{
            $this->assign("isCartNum","0");
        }

        $this->assign("GoodInfo",$arr);
        $this->assign("cartNum",$cartNum);
        $this->assign("cartPrice",$cartPrice);
        $this->display();
    }

    // “立即购买”  id 为商品ID
    function buy($id='')
    {
        $data['id']='';
        $data['user_id']=session("userID");
        $data['goods_id']=$id;
        $arr=$this->Goods->where("id=".$id)->find();
        $data['goods_sn']=$arr['goods_sn'];
        $data['name']=$arr['name'];
        $data['market_price']=$arr['market_price'];
        $data['shop_price']=$arr['shop_price'];
        $data['number']="1";
        $data['type']="0";
        if($arr['number']<$data['number'])
        {
            $this->error("库存数量不足");
        }else{
            $yanG1=$this->Cart->data($data)->add();
            $url=U('Order/cart');
            if($yanG1==true)
            {
                $this->Cart->commit();
                $this->success("已加入购物车",$url);
            }else{
                $this->Cart->rollback();
                $this->error("加入购物车失败");
            }
        }

    }
}